import React, { FC, useState, useEffect,useRef,useMemo } from 'react'
// import {produce} from 'immer'
import QuestionCard from '../../components/QuestionCard.tsx'
import { useSearchParams } from 'react-router-dom'
import { useRequest, useTitle,useDebounceFn, } from 'ahooks'
import { Typography,Empty,Spin } from 'antd'
import ListSearch from '../../components/ListSearch.tsx'
import { getQuestionListService } from '../../service/question.ts'
// import useLoadQuestionListData from '../../hooks/useLoadQuestionListData.ts'
import './common.css'
// 组件是一个函数（执行返回 JSX 片段），组件初次渲染执行这个函数
// 任何 state 更新，都会触发组件的更新（重新执行函数）
const {Title} = Typography
const List2: FC = () => {
  useTitle('小董问卷-我的问卷')
  const [searchParams] = useSearchParams() // url 参数虽然没有 page pageSize,但是有 keyword
  // console.log('keyword',searchParams.get('keyword'));
  
  // const [list,setList] = useState([])
  // const [total,setTotal] = useState(0)
  // 1、传统方式
  // useEffect(() => {
  //   async function load() {
  //     const data = await getQuestionListService()
  //     const { list = [], total = 0 } = data
  //     setList(list)
  //     setTotal(total)
  //   }
  //   load()
  // }, []) // 无依赖，组件初次渲染时执行

  // 2、useRequest
  // const { data = {}, loading } = useRequest(getQuestionListService)
  // const { list =[], total = 0 } = data 

  // 3、本地模拟方式
  // const [count, setCount] = useState(0)
  // const [questionList,setQuestionList] = useState([
  //   { id: 'q1', title: '问卷1', isPublished: false, isStar:true, answerCount:10,createAt:'2025-04-10' },
  //   { id: 'q2', title: '问卷2', isPublished: true, isStar:false, answerCount:11,createAt:'2025-05-11' },
  //   { id: 'q3', title: '问卷3', isPublished: false, isStar:false, answerCount:12,createAt:'2025-06-12' },
  //   { id: 'q4', title: '问卷4', isPublished: true, isStar:true, answerCount:13,createAt:'2025-07-13' },
  // ])

  // useEffect(() => {
  //   console.log('question list changed')
  // }, [questionList])

  // 4、hooks封装
  // const { data = {}, loading } = useLoadQuestionListData()
  // const { list = [], total = 0 } = data 

  // 5、上滑加载更多
  const [started, setStated] = useState(false) // 是否已经开始加载
  const [page, setPage] = useState(1) // List内部数据 数据不在url中体现
  const [list, setList] = useState([])
  const [total, setTotal] = useState(0)
  const haveMoreData = total > list.length // 是否还有未加载的数据


  // 尝试触发加载
  // const tryLoadMore = ()=>{
  //   console.log('try loadMore');
  // }

  // 尝试触发加载--防抖
  const containerRef = useRef<HTMLDivElement>(null)
  const { run: tryLoadMore } = useDebounceFn(()=>{
          const elem = containerRef.current
          if(elem == null) return 
          const domRect = elem.getBoundingClientRect()
          if(domRect == null) return 
          const { bottom } = domRect
          // console.log('bottom',bottom);
          // console.log('document.body.clientHeight',document.body.clientHeight);
          if(bottom <= document.body.clientHeight){
            console.log('执行加载');
            load()
            setStated(true)
          }
    },{
      wait: 1000
    }
  )

  // keyword变化时重置信息,设置搜索联动
  const keyword = searchParams.get('keyword') || ''
  useEffect(()=>{
    setStated(false)
    setPage(1)
    setList([])
    setTotal(0)
  },[keyword])

  // 真正加载
  const { loading, run:load } = useRequest(async ()=>{
    const data = await getQuestionListService({
      page,
      pageSize:10,
      keyword
    })
    return data
  },{ 
    manual: true,
    onSuccess(result){
      const { list: l = [], total = 0 } = result
      setList(list.concat(l)) // 累计
      setTotal(total)
      setPage(page+1)
    }
  })

  


  //1、 当页面加载，或者 url参数(keyword)变化时，触发加载
  useEffect(()=>{
    tryLoadMore() // 初始化
  },[searchParams,tryLoadMore])

  //2、 当页面滚动时，要尝试触发加载
  useEffect(()=>{
    // console.log('haveMoreData',haveMoreData)
    if(haveMoreData){
      window.addEventListener('scroll', tryLoadMore)
    }

    return ()=>{
      window.removeEventListener('scroll',tryLoadMore)
    }
  },[searchParams,haveMoreData,tryLoadMore])

  // 优化loadMore
  const LoadMoreContentElem = useMemo(()=>{
    if(!started || loading) return <Spin />
    if(total === 0) return <Empty description="暂无数据" />
    if(!haveMoreData) return <span>没有更多了</span>
    return <span>开始加载下一页</span>
  },[started,loading,total,haveMoreData])

  return (
    <div>
      <div className="ListHeader">
        <div className="left"><Title level={4}>我的问卷来了</Title></div>
        <div className="right"><Title level={5}><ListSearch /></Title></div>
      </div>
      <div className="ListContent">
        {/* <div style={{height:500}}></div> */}
        {/* {loading && (
          <div style={{textAlign:'center'}}><Spin /></div>
        )} */}
        { list.length > 0 && list.map((question:any) => {
          const { id, title, isPublished,isStar,answerCount,createdAt } = question
          return (
            <QuestionCard
              key={id}
              id={id}
              title={title}
              isPublished={isPublished}
              isStar={isStar}
              answerCount={answerCount}
              createdAt={createdAt}
            />
          )
        })}
        {/* {!loading && list.length === 0 && <Empty />} */}
      </div>
      <div className="ListFooter" ref={containerRef}>{LoadMoreContentElem}</div>
    </div>
  )
}

export default List2
